package core.app.zxing;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.view.KeyEvent;
import android.view.SurfaceView;
import android.view.View;

import com.example.heizhu.appfuncore.BaseAppCompatActivity;
import com.example.heizhu.appfuncore.R;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.Result;
import com.google.zxing.ResultPoint;

import core.android.camera.CameraManager;
import core.android.deeplinks.deeplinking.annotations.DeeplinkRoute;
import core.android.tools.AK;
import core.android.tools.T;
import rx.functions.Action1;

/**
 * 二维码扫描
 */
@DeeplinkRoute("qrcode")
public final class CaptureActivity extends BaseAppCompatActivity implements CameraManager.QrResultCallback {

    private ViewfinderView viewfinderView;
    private BeepManager beepManager;
    private AmbientLightManager ambientLightManager;

    @Override
    public void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        setContentView(R.layout.capture);
        beepManager = new BeepManager(this);
        ambientLightManager = new AmbientLightManager(this);

        //检查相机权限
        if (!checkPermission(this, Manifest.permission.CAMERA)) {
            showPermissionDialog(this, Manifest.permission.CAMERA);
        }
        AK.d();
    }

    public static boolean checkPermission(final Activity activity, final String permission) {
        if (Build.VERSION.SDK_INT >= 23) {
            int storagePermission = ActivityCompat.checkSelfPermission(activity, permission);
            if (storagePermission != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

    public static void showPermissionDialog(final Activity activity, final String permission) {
        new AlertDialog.Builder(activity)
                .setMessage("为了在Android M上使用摄像头.")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (!ActivityCompat.shouldShowRequestPermissionRationale(activity, permission)) {
                            ActivityCompat.requestPermissions(activity, new String[]{permission}, 100);
                            return;
                        }
                        ActivityCompat.requestPermissions(activity, new String[]{permission}, 100);
                    }
                }).show();

    }


    @Override
    protected void onResume() {
        super.onResume();
        AK.d();
        // CameraManager must be initialized here, not in onCreate(). This is necessary because we don't
        // want to open the camera driver and measure the screen size if we're going to show the help on
        // first launch. That led to bugs where the scanning rectangle was the wrong size and partially
        // off screen.
//        cameraManager = new CameraManager(getApplication());
        SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
        viewfinderView = (ViewfinderView) findViewById(R.id.viewfinder_view);

        CameraManager.INSTANCE.onResume(this, surfaceView);
        CameraManager.INSTANCE.setQrResultCallback(this);//设置扫描成功回调
        CameraManager.INSTANCE.setViewfinderView(viewfinderView);

        resetStatusView();
//        setRequestedOrientation(getCurrentOrientation());
//        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);//条形码只能横屏扫

        beepManager.updatePrefs();
        ambientLightManager.start();


    }

    @Override
    protected void onPause() {
        ambientLightManager.stop();
        beepManager.close();
        CameraManager.INSTANCE.onPause();
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                setResult(RESULT_CANCELED);
                finish();
                break;
            case KeyEvent.KEYCODE_FOCUS:
            case KeyEvent.KEYCODE_CAMERA:
                // Handle these events so they don't launch the Camera app
                return true;
            // Use volume up/down to turn on light
            case KeyEvent.KEYCODE_VOLUME_DOWN:
                CameraManager.INSTANCE.setTorch(false);//音量-关闭闪光灯
                return true;
            case KeyEvent.KEYCODE_VOLUME_UP:
                CameraManager.INSTANCE.setTorch(true);//音量+开启闪光灯
                return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * Superimpose a line for 1D or dots for 2D to highlight the key features of the barcode.
     * 往bitmap画上二维码的定位点
     *
     * @param barcode     A bitmap of the captured image.
     * @param scaleFactor amount by which thumbnail was scaled
     * @param rawResult   The decoded results which contains the points to draw.
     */
    private void drawResultPoints(Bitmap barcode, float scaleFactor, Result rawResult) {
        ResultPoint[] points = rawResult.getResultPoints();
        if (points != null && points.length > 0) {
            Canvas canvas = new Canvas(barcode);
            Paint paint = new Paint();
//            paint.setColor(getResources().getColor(R.color.result_points));
            if (points.length == 2) {
                paint.setStrokeWidth(4.0f);
                drawLine(canvas, paint, points[0], points[1], scaleFactor);
            } else if (points.length == 4 &&
                    (rawResult.getBarcodeFormat() == BarcodeFormat.UPC_A ||
                            rawResult.getBarcodeFormat() == BarcodeFormat.EAN_13)) {
                // Hacky special case -- draw two lines, for the barcode and metadata
                drawLine(canvas, paint, points[0], points[1], scaleFactor);
                drawLine(canvas, paint, points[2], points[3], scaleFactor);
            } else {
                paint.setStrokeWidth(10.0f);
                for (ResultPoint point : points) {
                    if (point != null) {
                        canvas.drawPoint(scaleFactor * point.getX(), scaleFactor * point.getY(), paint);
                    }
                }
            }
        }
    }

    private static void drawLine(Canvas canvas, Paint paint, ResultPoint a, ResultPoint b, float scaleFactor) {
        if (a != null && b != null) {
            canvas.drawLine(scaleFactor * a.getX(),
                    scaleFactor * a.getY(),
                    scaleFactor * b.getX(),
                    scaleFactor * b.getY(),
                    paint);
        }
    }

    private void resetStatusView() {
        viewfinderView.setVisibility(View.VISIBLE);
    }

    public void drawViewfinder() {
        viewfinderView.drawViewfinder();
    }

    private static Action1<String> resultAction;

    boolean isTorch;

    public void flash(View view) {
        AK.d("点击了闪关灯isTorch=" + isTorch);
        if (!isTorch) {
            CameraManager.INSTANCE.setTorch(true);
            isTorch = true;
        } else {
            CameraManager.INSTANCE.setTorch(false);
            isTorch = false;
        }
    }

    @Override
    public void onresult(Result result) {
        beepManager.playBeepSoundAndVibrate();
        AK.e("扫描完成:" + result);
        T.s(result);
    }
}
